package com.qf.controller;

import com.qf.entity.SysUser;
import com.qf.service.SysUserService;
import com.qf.util.R;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;

/**
 * ==== 勤能补拙 ====
 *
 * @author dzz
 * @date 2025/4/21
 * <p>
 * ==== 行稳致远 进而有为 ====
 */
@Log4j2
@RestController
@RequestMapping("/sys")
public class SysUserController {
    private Logger logger = LogManager.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    HashMap<String, Object> map = new HashMap<>();
    /**
     * 系统用户登录
     */
    @PostMapping("/user/login")
    public R login(@RequestBody SysUser sysUser, HttpSession session){
        //根据用户名+密码查数据库，将信息存储到redis，查到返回token
        logger.debug("接收前端脚手架发出的信息{}",sysUser);
        SysUser user = sysUserService.login(sysUser);
        session.setAttribute("token",user);
        //如果查询到用户，返回token
        if (user != null) {
            Object token = UUID.randomUUID().toString();
            map.put("token",token);
            logger.debug("返回给前端的令牌{}",map);
            //返回给前端的令牌
            return R.ok(map);
        } else {
            //返回给前端的错误信息
            return R.fail("用户名或密码错误");
        }
    }
    /**
     * 获取用户信息
     */
    @GetMapping("/user/info")
    public R info(HttpSession session){
        SysUser token = (SysUser) session.getAttribute("token");
        return R.ok(token);
    }
    @GetMapping("/user/logout")
    public R logout(String token){
        map.remove(token);
        return R.ok("退出成功");
    }
}
